<?php
declare(strict_types=1);

namespace app\admin\controller;

use app\admin\service\AliOosService;
use app\admin\service\CommunityRejectService;
use app\admin\service\EnterpriseService;
use app\admin\service\CommunityService;
use app\admin\service\IndustryCateService;
use app\admin\service\SubscribeLogService;
use app\admin\service\UsersService;
use app\admin\validate\Community as CommunityValidate;
use app\AdminController;
use think\exception\ValidateException;

/**
 * 社群管理(新)
 * Class Community
 * @package app\admin\controller
 */
class Community extends AdminController
{
    /**
     * 社群列表
     * @return \think\response\Json|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index()
    {
        $where = [];
        if (request()->isPost()) {
            // 关键词搜索
            $keywords = trim($this->request->param('keywords', ''));
            if ($keywords) {
                $where[] = ['r.name|c.name|e.name|u.nickname', 'like', '%' . $keywords . '%'];
            }

            $where[] = ['r.status', '=', 1];
            $list = CommunityService::getCommunityList($where, $this->page, $this->pagesize);
            $count = CommunityService::countCommunityList($where);

            return adminResponseJson(['list' => $list, 'count' => $count]);
        }

        return view();
    }

    /**
     * 社群发布
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function communityAdd()
    {
        if (request()->isPost()) {
            $data = request()->post();

            try {
                validate(CommunityValidate::class)->communityInsert()->check($data);
            } catch (ValidateException $e) {
                $this->error($e->getMessage());
            }

            $users = UsersService::findUsers(['id' => $data['uid']]);
            if (!$users) {
                $this->error(adminJsonMsg(10010));
            }

            $data['unique_key'] = md5($data['name']);
            $info = CommunityService::findCommunity([
                ['unique_key', '=', $data['unique_key']],
                ['status', '<>', 2],
            ]);
            if ($info) {
                $this->error(adminJsonMsg(10026));
            }

            // 企业数据
            $enterprise = EnterpriseService::findEnterprise(['id' => $data['eid']]);
            if (!$enterprise) {
                $this->error(adminJsonMsg(10027));
            }

            // 未重新选择/自定义行业，获取企业的行业
            if (!$data['cid'] && !$data['other_cate']) {
                $data['cid'] = $enterprise['cid'];
            }

            $cidArr = $this->createOtherCate($data['other_cate'], $data['cid']);
            // 一级id
            $data['pid'] = $cidArr['pid'];
            // 二级id
            $data['cid'] = $cidArr['cid'];

            $pathArr = [];
            $pathArr[] = $data['qrcode'];
            // 未重新选择行业，获取企业的logo
            if (!$data['logo']) {
                $data['logo'] = $enterprise['logo'];
            } else {
                $pathArr[] = $data['logo'];
            }

            // 1 => 已通过
            $data['status'] = 1;

            CommunityService::createCommunity($data);

//            AliOosService::uploadAliOos($pathArr);

            $this->success(adminJsonMsg(1004), (STRING)url('/community/index'));
        }

        // 企业数据
        $list['enterprise'] = EnterpriseService::getEnterprise();
        // 社群行业
        $list['industryCate'] = IndustryCateService::getIndustryCate();

        return view('', ['list' => $list]);
    }

    /**
     * 社群编辑
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function communityEdit()
    {
        $id = intval($this->request->param('id', 0));
        if (!$id) {
            $this->error(adminJsonMsg(1001));
        }

        $info = CommunityService::findCommunity(['id' => $id]);
        if (!$info) {
            $this->error(adminJsonMsg(1002));
        }

        $info['yqrcode'] = $info['qrcode'] ? config('url.url') . $info['qrcode'] : '';
        $info['ylogo'] = $info['logo'] ? config('url.url') . $info['logo'] : '';

        if (request()->isPost()) {
            $data = request()->post();

            try {
                validate(CommunityValidate::class)->check($data);
            } catch (ValidateException $e) {
                $this->error($e->getMessage());
            }

            $users = UsersService::findUsers(['id' => $data['uid']]);
            if (!$users) {
                $this->error(adminJsonMsg(10010));
            }

            // 企业数据
            $enterprise = EnterpriseService::findEnterprise(['id' => $data['eid']]);
            if (!$enterprise) {
                $this->error(adminJsonMsg(10027));
            }

            // 未重新选择/自定义行业，获取企业的行业
            if (!$data['cid'] && !$data['other_cate']) {
                $data['cid'] = $enterprise['cid'];
            }

            $cidArr = $this->createOtherCate($data['other_cate'], $data['cid']);
            // 一级id
            $data['pid'] = $cidArr['pid'];
            // 二级id
            $data['cid'] = $cidArr['cid'];

            $pathArr = [];
            // 修改了二维码
            if ($data['qrcode'] != $info['qrcode']) {
                $pathArr[] = $data['qrcode'];
            }

            // 未重新选择行业，获取企业的logo
            if (!$data['logo']) {
                $data['logo'] = $enterprise['logo'];
            } else {
                // 上传了logo，判断是否修改了
                if ($data['logo'] != $info['logo']) {
                    $pathArr[] = $data['logo'];
                }
            }

            CommunityService::updateCommunity($data, ['id' => $data['id']]);

            AliOosService::uploadAliOos($pathArr);

            $this->success(adminJsonMsg(1004), (STRING)url('/community/index'));
        }

        // 企业数据
        $list['enterprise'] = EnterpriseService::getEnterprise();
        // 一级社群分类
        $list['topCate'] = IndustryCateService::getIndustryCate();
        // 当前二级社群分类所属pid
        $info['pid'] = IndustryCateService::findIndustryCateValue(['id' => $info['cid']], 'pid');
        // 二级社群分类
        $list['childCate'] = IndustryCateService::getIndustryCate($info['pid']);

        return view('', ['info' => $info, 'list' => $list]);
    }

    /**
     * 社群详情
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function communityShow()
    {
        $id = intval($this->request->param('id', 0));
        if (!$id) {
            $this->error(adminJsonMsg(1001));
        }

        $info = CommunityService::findCommunity(['id' => $id], 1);

        return view('', ['info' => $info, 'source' => intval($this->request->param('source', 0))]);
    }

    /**
     * 修改状态
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function changeStatus()
    {
        if (request()->isPost()) {

            $id = intval($this->request->param('id', 0));
            // 2=>删除  1=>通过  -1=>驳回
            $status = intval($this->request->param('status', 2));
            // 驳回原因
            $reason = $this->request->param('reject_reason', '');
            if (!$id) {
                $this->error(adminJsonMsg(1001));
            }

            $where = ['id' => $id];
            $info = CommunityService::findCommunity($where);
            if (!$info) {
                $this->error(adminJsonMsg(1002));
            }

            $update = ['status' => $status];
            CommunityService::updateCommunity($update, $where);

            if ($status == -1) {
                // 写入驳回记录表
                CommunityRejectService::createCommunityReject([
                    'resid' => $id,
                    'reason' => $reason,
                    'reject_time' => time(),
                ]);
            }

            // 通过/驳回，推送消息
            if (in_array($status, [1, -1])) {
                $map = [
                    // 关联表id
                    'relation_id' => $id,
                    'uid' => $info['uid'],
                    // 1企业  2社群  3招聘
                    'type' => 2,
                    'is_push' => 0
                ];
                SubscribeLogService::updateSubscribeLog($map, [
                    'status' => $status
                ]);
            }

            $this->success(adminJsonMsg(1004));
        }
    }
}